<template>
  <div class="main-container">
    <!-- 左侧会话列表 -->
    <div class="left-sidebar">
      <div class="session-header">
        <el-button
          type="primary"
          class="new-chat-btn"
          @click="handleNewSession"
        >
          新对话
        </el-button>
      </div>
      <el-menu
        class="session-list"
        :default-active="sessionId.toString()"
        @select="handleSelectSession"
      >
        <el-menu-item
          v-for="session in sessions"
          :key="session.id"
          :index="session.id.toString()"
          class="session-item"
        >
          <div class="session-info">
            <div class="session-name">{{ session.name }}</div>
          </div>
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-icon class="el-icon--right">
                <el-icon><MoreFilled /></el-icon>
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="handleRename(session.name, session.id)"
                  >重命名</el-dropdown-item
                >
                <el-dropdown-item
                  divided
                  @click="handleDeleteSession(session.id)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <el-dialog v-model="dialogFormVisible" title="重命名" width="400">
      <el-input v-model="rename" autocomplete="off" />

      <el-button type="primary" @click="handleRenameSubmit()"> 提交 </el-button>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { SessionType } from "@ts/session";
import { httpClient } from "@/libs/http-client";
import { ElMessage } from "element-plus";
const emit = defineEmits(["sessionIdChange"]);

const dialogFormVisible = ref(false);

// 会话数据
const sessions = ref<Array<SessionType>>([]);
// 当前会话
const sessionId = ref(0);
//向外抛出sessionId变化的事件
watch(sessionId, (newValue) => {
  console.log("sessionId变化了", newValue);
  emit("sessionIdChange", newValue);
});

onMounted(async () => {
  // 初始化会话列表
  await getSessions();
  console.log("sessions:", sessions.value);
  // 如果有会话，切换到第一个会话
  if (sessions.value.length > 0) {
    console.log("切换到第一个会话");
    sessionId.value = sessions.value[0].id;
  }
  //如果没有会话,则生成一个新的会话
  else {
    console.log("没有会话,生成新的会话");
    handleNewSession();
  }
});

// 会话列表获取
const getSessions = async () => {
  await httpClient.get<Array<SessionType>>("/session/getAll").then((data) => {
    sessions.value = data;
  });
};

// 新建会话
const handleNewSession = () => {
  //使用httpClient.post
  httpClient.post<SessionType>("/session/create", {}).then((data) => {
    sessions.value.unshift(data);
    sessionId.value = data.id;
  });
};

// 选择会话
const handleSelectSession = (index) => {
  sessionId.value = index;
};

// 删除会话
const handleDeleteSession = (delSessionId) => {
  // 删除会话
  httpClient.delete(`/session/delete/${delSessionId}`).then(() => {
    const index = sessions.value.findIndex((s) => s.id === delSessionId);
    if (index !== -1) {
      sessions.value.splice(index, 1); // 删除数组中的元素
      //如果删除的是当前会话，切换到第一个会话
      if (sessionId.value == delSessionId) {
        console.log("切换到第一个会话");
        sessionId.value = sessions.value[0].id;
      }
    }
  });
};

const rename = ref("");
const renameId = ref(0);
// 重命名会话窗口
const handleRename = (name, sessionId) => {
  console.log("重命名会话窗口");
  dialogFormVisible.value = true;
  rename.value = name;
  renameId.value = sessionId;
};
// 提交重命名请求
const handleRenameSubmit = () => {
  httpClient
    .put(`/session/rename/${renameId.value}`, null, {
      params: { newName: rename.value },
    })
    .then((data) => {
      const index = sessions.value.findIndex((s) => s.id === renameId.value);
      if (index !== -1) {
        sessions.value[index].name = data.name;
        //关闭窗口
        dialogFormVisible.value = false;
        ElMessage.success("重命名成功");
      }
    });
};
</script>


<style scoped>
.main-container {
  height: 100%;
  width: 100%;
}

.left-sidebar {
  height: calc(100vh - 60px);
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.session-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.session-list {
  border-right: none;
  height: 100%;
  flex: 1;
  overflow-y: auto;
}

.new-chat-btn {
  width: 100%;
}

.session-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 72px;
  padding: 0 16px;
}

.session-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.session-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.session-date {
  font-size: 12px;
  color: #999;
}

.delete-btn {
  margin-left: auto;
}
</style>
